package com.personal.error;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 全局异常捕获处理器
 * 1.捕获返回json格式
 * 2.捕获返回错误页面
 */
@ControllerAdvice(basePackages = "com.personal.controller")
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = RuntimeException.class)
    @ResponseBody
    public Map<String, Object> errorResult(HttpServletRequest request, RuntimeException exception){
        //实际开发中记录到日志中
        Map<String, Object> errorMap = new HashMap<>();
        errorMap.put("errorCode",500);
        errorMap.put("errorMessage","系统错误");
        //日志打印出异常信息
        log.info("request url:"+request.getRequestURL().toString());
        log.info("runtime exception:"+exception.getMessage());
        return errorMap;
    }
}
